<script setup>
import { useRoute, useRouter } from "vue-router";
import { queryNewsInfo, queryStoryExtra } from "@/api";
import { reactive, onBeforeMount, onBeforeUnmount, nextTick } from "vue";

const route = useRoute(),
  router = useRouter();

// 获取路径参数传递的ID
const id = route.params.id;

// 初始化状态
let state = reactive({
  info: null,
  popularity: 0,
  comments: 0,
});

// 第一次渲染之前：获取相关数据
let link;
onBeforeMount(async () => {
  try {
    let result = await queryNewsInfo(id);
    state.info = result;
    // 动态绑定CSS样式
    let css = result.css && result.css[0];
    if (css) {
      link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = css;
      document.head.appendChild(link);
    }
    // 动态插入封面图
    nextTick(() => {
      let imgBox = document.querySelector(".img-place-holder"),
        image = result.image;
      if (!imgBox) return;
      if (!image) {
        imgBox.parentNode.parentNode.removeChild(imgBox.parentNode);
        return;
      }
      let img = new Image();
      img.src = image;
      img.onload = () => {
        imgBox.appendChild(img);
      };
      img.onerror = () => {
        imgBox.parentNode.parentNode.removeChild(imgBox.parentNode);
      };
    });
  } catch (_) {}
});
onBeforeMount(async () => {
  try {
    let { popularity, comments } = await queryStoryExtra(id);
    state.popularity = popularity;
    state.comments = comments;
  } catch (_) {}
});

// 释放之前
onBeforeUnmount(() => {
  if (link) document.head.removeChild(link);
});
</script>

<template>
  <van-skeleton title :row="5" v-if="!state.info" />
  <div class="contentMy" v-else v-html="state.info.body"></div>

  <div class="nav-box">
    <van-icon name="arrow-left" @click="$router.go(-1)"></van-icon>
    <van-icon name="comment-o" :badge="state.comments"></van-icon>
    <van-icon name="good-job-o" :badge="state.popularity"></van-icon>
    <van-icon name="star-o" color="#ccc"></van-icon>
    <!-- #1989fa -->
    <van-icon name="share-o" color="#ccc"></van-icon>
  </div>
</template>

<style lang="less" scoped>
.contentMy {
  background: #fff;
  padding-bottom: 50px;
  margin: 0;

  :deep(.img-place-holder) {
    height: 375px;
    overflow: hidden;

    img {
      display: block;
      margin: 0;
      width: 100%;
      min-height: 100%;
    }
  }
}

.van-skeleton {
  padding: 30px 15px;
}

.nav-box {
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0 15px;
  width: 100%;
  height: 50px;
  background: #f4f4f4;
  font-size: 22px;

  .van-icon:nth-child(1) {
    position: relative;

    &::after {
      position: absolute;
      top: -10%;
      right: -15px;
      content: "";
      width: 1px;
      height: 120%;
      background: #d5d5d5;
    }
  }

  :deep(.van-badge) {
    background-color: transparent;
    border: none;
    color: #000;
    right: -5px;
  }
}
</style>